<template>
  <div class="content_padding">
		<div class="container" style="position: fixed; top: 0;left: 0;">
      <span class="staffTitle">{{ staffTitle }}</span>
      <div>
        <el-button type="text" icon="icon iconfont iconfanhui" @click="returnPreviousPage">返回</el-button>
        <el-button type="text" icon="el-icon-position" @click="addStaff">提交</el-button>
      </div>
    </div>

		<div class="device_info">
			<div class="title">基本信息</div>
			<template>
				<div class="info-box" style="display: flex;margin-top: 30px;">
					<span class="txt"><span class="element_color">*</span>面部照片：</span>
          <div class="editor-after">
            <div class="img-width">
              <div style="position: relative; display: flex;" v-for="(item, index) in srcList" :key="index">
                <el-image class="plan-image" :src="item" fit="cover" :preview-src-list="srcList"></el-image>
                <i class="el-icon-remove remove-icon" @click="delPicList(index)"></i>
              </div>
              <el-upload
                action="#"
                accept="image/jpeg, image/jpg"
                :show-file-list="false"
                :on-change="onUploadChange"
                name="file"
                list-type="picture"
                :auto-upload="false">
                <div class="upload" v-show="srcList.length < 1">
                  <i class="el-icon-plus"></i>
                </div>
              </el-upload>
            </div>
          </div>
				</div>

				<div class="basic_info">
					<div class="info-box">
						<span class="txt"><span class="element_color">*</span>姓名：</span>
						<el-input v-model="user.fullname" size="medium" class="input-width" clearable placeholder="请输入" />
					</div>
          <div class="info-box">
            <span class="txt">电话：</span>
            <el-input v-model="user.phone" size="medium" maxlength="11" class="input-width" clearable placeholder="请输入" />
          </div>
					<div class="info-box">
						<span class="txt">籍贯：</span>
						<el-input v-model="user.nativePlace" size="medium" class="input-width" clearable placeholder="请输入" />
					</div>
          <div class="info-box">
            <span class="txt"><span class="element_color">*</span>ID号：</span>
            <el-input v-model="user.username" size="medium" class="input-width" clearable placeholder="请输入" />
          </div>
					<div class="info-box">
						<span class="txt">出生日期：</span>
						<el-date-picker
							class="input-width"
              size="medium"
							v-model="user.birthday"
							type="date"
							value-format="yyyy-MM-dd"
							placeholder="选择日期" />
					</div>
					<div class="info-box">
						<span class="txt">婚姻：</span>
						<el-select v-model="user.maritalStatus" size="medium" class="input-width" clearable placeholder="请选择" >
							<el-option v-for="item in marriage" :key="item.dicid" :label="item.itemvalue" :value="item.dicid" />
						</el-select>
					</div>
					<div class="info-box">
						<span class="txt">性别：</span>
						<el-select v-model="user.title" size="medium" class="input-width" placeholder="请选择" >
							<el-option v-for="item in sex" :key="item.id" :label="item.name" :value="item.id" />
						</el-select>
					</div>
					<div class="info-box">
						<span class="txt">身体状况：</span>
						<el-input v-model="medicalReportImg" size="medium" class="input-width" clearable placeholder="请输入" />
					</div>
					<div class="info-box">
						<span class="txt">学历：</span>
						<el-select v-model="user.education" size="medium" class="input-width" clearable placeholder="请选择" >
							<el-option v-for="item in educationInfo" :key="item.dicid" :label="item.itemvalue" :value="item.dicid" />
						</el-select>
					</div>
					<div class="info-box">
						<span class="txt">血型：</span>
						<el-select v-model="user.bloodType" size="medium" class="input-width" clearable placeholder="请选择" >
							<el-option v-for="item in bloodTypeInfo" :key="item.dicid" :label="item.itemvalue" :value="item.dicid" />
						</el-select>
					</div>
					<div class="info-box">
						<span class="txt">家庭住址：</span>
						<el-input v-model="user.address" size="medium" class="input-width" clearable placeholder="请输入" />
					</div>
					<div class="info-box">
						<span class="txt">邮箱：</span>
						<el-input v-model="user.email" size="medium" class="input-width" clearable placeholder="请输入" />
					</div>
					<div class="info-box">
						<span class="txt">身份证号：</span>
						<el-input v-model="user.idNumber" size="medium" class="input-width" clearable placeholder="请输入" />
					</div>
					<div class="info-box">
						<span class="txt">签发机构：</span>
						<el-input v-model="user.idIssuer" size="medium" class="input-width" clearable placeholder="请输入" />
					</div>
					<div class="info-box">
						<span class="txt">政治面貌：</span>
						<el-select v-model="user.politicsStatus" size="medium" class="input-width" clearable placeholder="请选择" >
							<el-option v-for="item in politicsStatusInfo" :key="item.dicid" :label="item.itemvalue" :value="item.dicid" />
						</el-select>
					</div>

					<div class="info-box">
						<span class="txt">有效开始时间：</span>
						<el-date-picker
							class="input-width"
              size="medium"
							v-model="user.idStartTime"
							type="date"
							value-format="yyyy-MM-dd"
							placeholder="选择日期" />
					</div>
					<div class="info-box">
						<span class="txt">有效截止时间：</span>
						<el-date-picker
							class="input-width"
              size="medium"
							v-model="user.idEndTime"
							type="date"
							value-format="yyyy-MM-dd"
							placeholder="选择日期" />
					</div>
          <div class="info-box">
            <span class="txt">紧急联系电话：</span>
            <el-input v-model="user.emergencyCall" size="medium" maxlength="11" class="input-width" clearable placeholder="请输入" />
          </div>
				</div>
			</template>
		</div>

		<div class="device_info">
			<div class="title">工作信息</div>
			<div class="basic_info" style="margin: 10px 0;">
        <div class="info-box">
          <span class="txt"><span class="element_color">*</span>标段：</span>
          <el-select
            v-model="detail.bidSection"
            size="medium"
            class="input-width"
            placeholder="请选择"
            @change="getWorkAreaList(null)">
            <el-option v-for="item in biaoduanList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </div>
				<div class="info-box">
					<span class="txt"><span class="element_color">*</span>所属组织：</span>
					<el-select v-model="detail.depid" size="medium" class="input-width" placeholder="请选择" @change="getGroupList(null)">
						<el-option v-for="item in organize" :key="item.depId" :label="item.depName" :value="item.depId" />
					</el-select>
				</div>
        <div class="info-box">
          <span class="txt"><span class="element_color">*</span>班组：</span>
          <el-select v-model="detail.groupid" size="medium" class="input-width" placeholder="请先选择所属组织" >
            <el-option v-for="item in group" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </div>
        <div class="info-box">
          <span class="txt"><span class="element_color">*</span>所属工区：</span>
          <el-select v-model="workAreaId" size="medium" class="input-width" multiple placeholder="请先选择标段">
            <el-option v-for="item in workAreaInfo" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </div>
        <div class="info-box">
          <span class="txt"><span class="element_color">*</span>角色：</span>
          <el-select v-model="detail.roleid" size="medium" class="input-width" placeholder="请选择">
            <el-option v-for="item in role" :key="item.roleid" :label="item.rolename" :value="item.roleid" />
          </el-select>
        </div>
        <div class="info-box">
          <span class="txt"><span class="element_color">*</span>是否考勤：</span>
          <el-select v-model="detail.isReg" size="medium" class="input-width" placeholder="请选择">
            <el-option v-for="item in clockingIn" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </div>
<!--        <div class="info-box">-->
<!--          <span class="txt">负责班组：</span>-->
<!--          <el-select v-model="detail.groupid" size="medium" class="input-width" clearable placeholder="请选择" >-->
<!--            <el-option v-for="item in group" :key="item.id" :label="item.name" :value="item.id" />-->
<!--          </el-select>-->
<!--        </div>-->
				<div class="info-box">
					<span class="txt">入职时间：</span>
					<el-date-picker
						class="input-width"
            size="medium"
						v-model="detail.accessiontime"
						value-format="yyyy-MM-dd"
						type="date"
						placeholder="选择日期" />
				</div>
        <div class="info-box">
          <span class="txt">合同编号：</span>
          <el-input v-model="detail.contractNO" size="medium" class="input-width" clearable placeholder="请输入" />
        </div>
        <div class="info-box">
          <span class="txt">特殊工种：</span>
          <el-input v-model="detail.specialTypeWork" size="medium" class="input-width" clearable placeholder="请输入" />
        </div>
        <div class="info-box">
          <span class="txt">合同开始日期：</span>
          <el-date-picker
            class="input-width"
            size="medium"
            v-model="detail.contractStartTime"
            value-format="yyyy-MM-dd"
            type="date"
            placeholder="选择日期" />
        </div>
        <div class="info-box">
          <span class="txt">合同结束日期：</span>
          <el-date-picker
            class="input-width"
            size="medium"
            v-model="detail.contractEndTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择日期" />
        </div>
			</div>
		</div>
	</div>
</template>

<script>
import HttpInterface from "../../util/httpInterface";
import HttpConfig from "../../util/httpConfig";
import { mapState, mapActions } from "vuex";

export default {
  components: {},
  data() {
		return {
			staffTitle: "添加人员信息",
      srcList: [],
      organize: [],
      group: [],
      workAreaInfo: [],
      workAreaId: [],
			sex: [
				{ id : 0, name: "女" },
				{ id : 1, name: "男" }
			],
      clockingIn: [
        { id : 0, name: "否" },
        { id : 1, name: "是" }
      ],
      medicalReportImg: "", //身体状况
      user: {
        photo: "",//头像地址
        username: "",//用户编号
        fullname: "",//真实姓名
        title: 1,//性别
        education: 33,//学历
        phone: "",//手机号
        email: "",//邮箱
        bloodType: 27,//血型
        nativePlace: "",//籍贯
        maritalStatus: 16,//婚姻状态
        politicsStatus: 42,//政治面貌
        birthday: "",//出生日期
        idNumber: "",//身份证号
        idIssuer: "",//签发机构
        idStartTime: "",//有效开始时间
        idEndTime: "",//有效结束时间
        emergencyCall: "",//紧急联系电话
        address: "",//家庭住址
			},
      detail: {
        roleid: null, //角色id
        specialTypeWork: "",//特殊工种持证
        bidSection: "",
        contractNO: "",//合同编号
        isReg: 0,
        contractStartTime: "",//合同开始日期
        contractEndTime: "",//合同结束日期
        depid: "",//所属组织
        accessiontime: "",//入职时间
        groupid: "", // 班组id
      }
		};
  },

  computed: {
    ...mapState(["biaoduanList", "organizations", "role", "marriage"]),
    ...mapState(["nature", "bloodTypeInfo", "educationInfo", "politicsStatusInfo"])
  },

  mounted() {
    // 如果没有标段数据 组织就拿所有组织数据
    if (this.biaoduanList.length == 0) this.organize = this.organizations;

    if (this.role) this.detail.roleid = this.role[0].roleid;
  },

  methods: {
    ...mapActions(["selectByBidSection"]),

    returnPreviousPage () {
      this.$parent.subPage = 0;
    },

    getWorkAreaList(id, groupId) {
      let _this = this;
      this.selectByBidSection({
        bidSection: this.detail.bidSection,
        fn: function (data) {
          _this.workAreaInfo = data;
        }
      })

      let { bidSection } = this.detail;
      if (!id) this.workAreaId = [];
      let params = { bidSection };
      HttpInterface.requestGet(this, HttpInterface.URL_DUTYMANAGE_FIND_ORG, params, res => {
        let { success, other } = res.data;
        if (success) {
          this.organize = other;
          if (other.length > 0) {
            this.detail.depid = other[0].depId;
            this.getGroupList(groupId);
          } else {
            this.detail.depid = "";
          }
        }
      })
    },

    getGroupList(groupId) {
      let params = {
        depId: this.detail.depid
      }
      HttpInterface.requestGet(this, HttpInterface.URL_GROUP_FIND_GROUP, params, res => {
        let { success, other } = res.data;
        if (success) {
          this.group = other;
          if (other.length > 0) {
            if (groupId) {
              this.detail.groupid = groupId;
            } else {
              this.detail.groupid = other[0].id;
            }
          } else {
            this.detail.groupid = "";
          }
        }
      })
    },

    refresh (id) {
      if (id != 0) {
        this.staffTitle = "编辑人员信息";
        this.getStaffDetail(id);
      }
		},

		// 编辑人员信息
	  getStaffDetail (id) {
		  var _this = this;
		  var params = { id };
		  HttpInterface.requestPost(this, HttpInterface.URL_DUTYUSER_DETAIL, params, function (response) {
			  var { success, other } = response.data;
			  if (success) {
			    let { user, detail } = other;
			    let arr = [];
          for (const key in user) detail[key] = user[key];

          _this.srcList = [HttpConfig.serverUrl + user.photo];
          _this.user = detail;
          _this.detail = detail;
          detail.workAreaList.forEach(item => {
            arr.push(item.id);
          })
          _this.workAreaId = arr;
          _this.user.education = Number(detail.education);
          _this.user.bloodType = Number(detail.bloodType);
          _this.user.maritalStatus = Number(detail.maritalStatus);
          _this.user.politicsStatus = Number(detail.politicsStatus);
          _this.detail.roleid = Number(detail.roleId);
          _this.medicalReportImg = detail.medicalReportImg;
          _this.getWorkAreaList(id, detail.groupId);
			  } else {
					_this.errorMessage('获取数据失败！');
				}
		  }, null);
		},

    delPicList(index) {
      this.srcList.splice(index, 1);
    },

    // 图片上传
    onUploadChange(file) {
      var _this = this;
      const isIMAGE = (file.raw.type === 'image/jpeg' || file.type === 'image/jpg');
      const isLt1M = file.size / 1024 / 1024 < 1;
      if (!isIMAGE) {
        this.$message.error('上传文件只能是图片格式!');
        return false;
      }
      if (!isLt1M) {
        this.$message.error('上传文件大小不能超过 1 MB!');
        return false;
      }
      var reader = new FileReader();
      reader.readAsDataURL(file.raw);
      reader.onload = function(e) {
        const src = e.target.result;
        if (_this.srcList.length <= 1) {
          _this.srcList.push(src)
          _this.user.photo = src;
        }
      }
    },

	  verifyFormInfo () {
	    let { photo, fullname, username } = this.user;
	    let { depid, groupid, roleid, bidSection } = this.detail;
		  if (!photo) {
			  this.warningMessage("请上传用户头像");
			  return false;
		  }
      if (!fullname) {
        this.warningMessage("请输入姓名");
        return false;
      }
      if (!username) {
        this.warningMessage("请输入ID号");
        return false;
      }
      if (!bidSection) {
        this.warningMessage("请选择标段");
        return false;
      }
      if (!depid) {
        this.warningMessage("请选择组织");
        return false;
      }
      if (!groupid) {
        this.warningMessage("请选择班组");
        return false;
      }
      if (this.workAreaId.length == 0) {
        this.warningMessage("请选择所属工区");
        return false;
      }
      if (!roleid) {
        this.warningMessage("请选择角色");
        return false;
      }
		  return true;
	  },

	  addStaff() {
      if (!this.verifyFormInfo()) return;
      var _this = this;
      let arr = [];
		  let { detail, user, workAreaId, workAreaInfo, medicalReportImg } = this;
      user.medicalReportImg = medicalReportImg;
      workAreaId.forEach(item => {
        workAreaInfo.forEach(key => {
          if (item == key.id) arr.push({ id: key.id, name: key.name });
        })
      })
      detail.workAreaList = arr;

      for (const key in user) {
        if (key !== "photo") detail[key] = user[key];
      }

      for (const key in detail) {
        if (key !== "workAreaList") user[key] = detail[key];
      }

		  let params = { detail, user };
      var url = user.userid ? HttpInterface.URL_DUTYUSER_EDIT : HttpInterface.URL_DUTYUSER_ADDUSER;
      HttpInterface.requestPost(this, url, params, function (response) {
			  var data = response.data;
        if (data.success) {
          _this.$parent.resetPresentPage();
          _this.successMessage('操作成功！');
        } else {
          _this.errorMessage(data.msg);
        }
		  },null, false)
	  }
	}
};
</script>

<style scoped lang="scss">
.content_padding{
	padding: 20px;
	box-sizing: border-box;
	margin-top: 20px;

  .device_info{
    margin-top: 30px;

    .basic_info{
      display: flex;
      flex-wrap: wrap;
    }

    .title{
      width: 100%;
      font-weight: bold;
      line-height: 50px;
      display: inline-block;
      border-bottom: 1px solid rgb(236, 236, 236);
    }
  }
}

.info-box{
	margin-right: 80px;
	margin-top: 18px;

  .upload_pic{
    margin-left: 5px;
    margin-top: -6px;
  }

  .input-width{
    width: 240px !important;
  }

  .txt{
    font-size: 14px;
    width: 126px;
    display: inline-block;
    text-align: right;
  }

  .element_color{
    color: #f44336;
    font-size: 12px;
    margin-right: 4px;
  }
}

.wire{
	width: 100%;
	height: 1px;
	background: rgb(236, 236, 236);
	margin-top: 30px;
}

/* 上传图片 */
.editor-after{
  display: flex;
  flex-wrap: wrap;
  margin-top: -8px;

  .img-width{
    display: flex;
    flex-wrap: wrap;

    .plan-image,
    .upload{
      width: 100px;
      height: 100px;
      border-radius: 4px;
      margin: 6px;
      border: 1px solid #cbcbd0;
      box-sizing: border-box;
    }

    .remove-icon{
      position: absolute;
      top: -5px;
      right: -4px;
      z-index: 99;
      font-size: 18px;
      color: rgb(247, 74, 74);
      border: 1px solid #fff;
      border-radius: 50%;
      background: #fff;
    }

    .upload{
      border: 1px dashed #cbcbd0;
      display: flex;
      justify-content: center;
      align-items: center;
      font-size: 26px;
      color: #999999;
      cursor: pointer;

      &:hover{
        border: 1px dashed #409EFF;
        background: rgb(246, 250, 255);
        color: #409EFF;
        transition: all 0.3s;
      }
    }
  }
}

.el-button--text >>> .iconfanhui{
  margin-right: 4px;
  font-size: 18px;
  vertical-align: -2px;
}
</style>
